import axios from 'axios'
import { ElMessage } from 'element-plus'
import { diffTokenTime } from '@/utils/auth'
import store from '@/store'
// import router from './router'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

service.interceptors.request.use(
  (config) => {
    if (localStorage.getItem('token')) {
      if (diffTokenTime()) {
        store.dispatch('app/logout')
        return Promise.reject(new Error('token 失效了'))
      }
    }
    return config
  },
  (error) => {
    return Promise.reject(new Error(error))
  }
)
service.interceptors.response.use(
  (res) => {
    if (res.data.code !== 2000) {
      ElMessage.error(res.data.msg)
      console.log('后端返回异常')
      return Promise.reject(new Error('1111'))
    } else {
      return res
    }
  },
  (e) => {
    console.log(e)
    if (e.request.code !== 2000) {
      console.log(e.request.code)
    }
  }
)
// service.interceptors.response.use(
//   (response) => {
//     const { data, meta } = response.data
//     console.log(data, meta)
//     if (meta.status === 200 || meta.status === 201) {
//       return data
//     } else {
//       ElMessage.error(meta.msg)
//       return Promise.reject(new Error(meta.msg))
//     }
//   },
//   (error) => {
//     console.log(error.response)
//     error.response && ElMessage.error(error.response.data)
//     return Promise.reject(new Error(error.response.data))
//   }
// )
// service.interceptors.response.use(
//   (response) => {
//     console.log(response.data)
//     const { data, code, msg } = response.data
//     console.log(data, msg)
//     if (data.status === 1 || code === 2000) {
//       return data
//     } else {
//       ElMessage.error(msg)
//       return Promise.reject(new Error(msg))
//     }
//   },
//   (error) => {
//     console.log(error.response)
//     error.response && ElMessage.error(error.response.data)
//     return Promise.reject(new Error(error.response.data))
//   }
// )

export default service
